#include<iostream>
#include<pthread.h>
#include<string>
#include<unistd.h>
using namespace std;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
int tickets=5;
void *threadRoutine(void*args)
{
    string name=static_cast<const char*>(args);
    while(true)
    { 
    sleep(1);
    pthread_mutex_lock(&mutex);
    if(tickets > 0)
        {
            std::cout << name<< ", get a ticket: " << tickets-- << std::endl; // 模拟抢票
            usleep(1000);
        }
        else
        {
           std::cout << "没有票了," << name << std::endl; // 就是每一个线程在大量的申请锁和释放锁
           // 1. 让线程在进行等待的时候，会自动释放锁 
           // 2. 线程被唤醒的时候，是在临界区内唤醒的，当线程被唤醒, 线程在pthread_cond_wait返回的时候，要重新申请并持有锁
           // 3. 当线程被唤醒的时候，重新申请并持有锁本质是也要参与锁的竞争的！！
           pthread_cond_wait(&cond, &mutex);
        }
    pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    pthread_t t1,t2,t3;
    pthread_create(&t1,nullptr,threadRoutine,(void*)"Thread 1");
    pthread_create(&t2,nullptr,threadRoutine,(void*)"Thread 2");
    pthread_create(&t3,nullptr,threadRoutine,(void*)"Thread 3");
    while(true)
    {
        sleep(5);
        pthread_mutex_lock(&mutex);
        tickets+=5;
        pthread_mutex_unlock(&mutex);
        pthread_cond_broadcast(&cond);
    }
    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);

}